/**
 * @copyright Copyright (c) 2025 CSG Digital Grid Technology (Guangdong) Co., Ltd.
 * @author Xie Jinhui
 */

#include "cpu.h"
#include "main.h"

#define COMPATIBLE_PATH "/proc/device-tree/cpus/cpu@0/compatible"
#define BUFFER_SIZE 256

// 定义错误代码
enum {
    SUCCESS = 0,
    ERROR_OPEN_FILE = 1,
    ERROR_READ_FILE = 2
};

int get_cpu_type(char *cpu_type)
{
    //printf("Reading compatible string from: %s\n", COMPATIBLE_PATH);
    int result = read_compatible_string(COMPATIBLE_PATH, cpu_type, BUFFER_SIZE);

    // 根据返回值处理不同的错误情况
    switch (result) {
        case SUCCESS:
            //printf("Read compatible string successfully.\n");
            break;
        case ERROR_OPEN_FILE:
            fprintf(stderr, "Failed to open file: %s\n", COMPATIBLE_PATH);
            break;
        case ERROR_READ_FILE:
            fprintf(stderr, "Failed to read file: %s\n", COMPATIBLE_PATH);
            break;
        default:
            fprintf(stderr, "Unknown error occurred.\n");
            break;
    }

}

int read_compatible_string(const char *path, char *content, size_t size) {
    int fd = open(path, O_RDONLY);
    if (fd == -1) {
        perror("open");
        return ERROR_OPEN_FILE;
    }

    // 读取文件内容到 content 缓冲区
    ssize_t bytesRead = read(fd, content, size - 1);
    if (bytesRead == -1) {
        perror("read");
        close(fd);
        return ERROR_READ_FILE;
    }

    // 确保缓冲区以 null 结尾
    content[bytesRead] = '\0';

    close(fd);

    // 打印兼容字符串
    //printf("Compatible string(s):\n");

    // char *ptr = content;
    // while (ptr < content + bytesRead) {
    //     printf("  %s\n", ptr);
    //     ptr += strlen(ptr) + 1; // 移动到下一个字符串
    // }

    return SUCCESS;
}